package com.tansun.easycare.rule.datamodel.web;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.core.utils.StringUtils;
import com.tansun.easycare.rule.common.DataCache;
import com.tansun.easycare.rule.common.DataSetTreeVo;
import com.tansun.easycare.rule.common.JsonMessage;
import com.tansun.easycare.rule.common.ResMessage;
import com.tansun.easycare.rule.common.RuleBaseController;
import com.tansun.easycare.rule.common.SelBean;
import com.tansun.easycare.rule.common.model.ResponseVO;
import com.tansun.easycare.rule.datamodel.dao.RuleEnumDao;
import com.tansun.easycare.rule.datamodel.entity.RuleEnum;
import com.tansun.easycare.rule.datamodel.service.DBtoDataModelService;
import com.tansun.easycare.rule.datamodel.service.RuleEnumService;
import com.tansun.rule.utils.LoggerManager;

/**
 * 枚举项管理Controller
 * 
 * @author hejiatai
 * @version 2017-12-08
 */
@Controller
@RequestMapping(value = "/ruleProj/enum")
public class RuleEnumController extends RuleBaseController {

	@Autowired
	private RuleEnumService ruleEnumService;
	
	@Autowired
	private RuleEnumDao ruleEnumDao;
	
	@Autowired
	private DBtoDataModelService dbtoDataModelService;
	
	@ModelAttribute
	public RuleEnum get(@RequestParam(required = false) String id) {
		RuleEnum entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = ruleEnumService.get(id);
		}
		if (entity == null) {
			entity = new RuleEnum();
		}
		return entity;
	}

	@RequestMapping(value = { "list", "" })
	public String list(RuleEnum ruleEnum, String projectCode,HttpServletRequest request, HttpServletResponse response, Model model)
			throws Exception {
		if (StringUtils.isEmpty(projectCode)) {
            projectCode = this.getCurrProjectCode();
            ruleEnum.setProjectCode(projectCode);
        }
		
		PageInfo<RuleEnum> page = ruleEnumService.findPage(new Page<RuleEnum>(), ruleEnum);
		model.addAttribute("page", page);
		model.addAttribute("re", ruleEnum);
		List<RuleEnum> list2 = new ArrayList<RuleEnum>();
		RuleEnum r = new RuleEnum();
		r.setProjectCode(projectCode);
		r.setSearchEnumType(true);	
		list2 = ruleEnumDao.findList(r);
		Map<String,String> types = new HashMap<String,String>();
		for(RuleEnum e:list2){
			types.put(e.getEnumCode(), e.getEnumName());
		}
		model.addAttribute("rankRelationId",request.getParameter("rankRelationId"));
		model.addAttribute("types", types);
		model.addAttribute("projectCode", projectCode);
		return "rule/datamodel/enummanage/ruleEnumList";
	}

	@RequestMapping(value = "save")
	@ResponseBody
	public ResMessage save(RuleEnum ruleEnum) {
		try {
			ruleEnum.setProjectCode(getCurrProjectCode());
			ruleEnumService.save(ruleEnum);
			DataCache.enumChange(getCurrProjectCode());
		} catch (Exception e) {
			e.printStackTrace();
			return new ResMessage("failure", "保存文件失败");
		}
		return new ResMessage("success", "保存成功");
	}

	@RequestMapping(value = "delete")
	@ResponseBody
	public ResMessage delete(@RequestParam("ids[]") String[] ids) {
		try {
			for (String id : ids) {
				RuleEnum e = new RuleEnum();
				e.setId(id);
				ruleEnumService.delete(e);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ResMessage("failure", "删除失败，读写文件出错或者会话过期，尝试刷新");
		}
		return new ResMessage("success", "删除成功");
	}
	
	@RequestMapping("update")
	@ResponseBody
	public ResponseVO updata(@RequestParam("id") String id) {
		ResponseVO responseVO = new ResponseVO();
		responseVO.setStatus(200);
		RuleEnum ruleEnum = this.ruleEnumService.get(id);
		responseVO.setData(ruleEnum);
		return responseVO;
	}

	@RequestMapping(value = { "typelist" })
	public String typelist(RuleEnum ruleEnum, HttpServletRequest request, HttpServletResponse response, Model model)
			throws Exception {
		ruleEnum.setProjectCode(this.getCurrProjectCode());
		ruleEnum.setSearchEnumType(true);
		PageInfo<RuleEnum> page = ruleEnumService.findPage(new Page<RuleEnum>(), ruleEnum);
		model.addAttribute("page", page);
		model.addAttribute("re", ruleEnum);
		model.addAttribute("rankRelationId",request.getParameter("rankRelationId"));
		model.addAttribute("pCode", this.getCurrProjectCode());
		return "rule/datamodel/enumtype/ruleEnumTypeList";
	}

	@RequestMapping(value = "typesave")
	@ResponseBody
	public ResMessage typesave(RuleEnum ruleEnum) {
		try {
			ruleEnum.setEnumType("枚举类型管理");
			ruleEnum.setProjectCode(getCurrProjectCode());
			ruleEnumService.save(ruleEnum);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResMessage("failure", "保存文件失败");
		}
		return new ResMessage("success", "保存成功");
	}

	@RequestMapping(value = "typedelete")
	@ResponseBody
	public ResMessage typedelete(@RequestParam("ids[]") String[] ids) {
		try {
			for (String id : ids) {
				RuleEnum e = new RuleEnum();
				e.setId(id);
				ruleEnumService.delete(e);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ResMessage("failure", "删除失败，读写文件出错或者会话过期，尝试刷新");
		}
		return new ResMessage("success", "删除成功");
	}

	@RequestMapping("typeupdate")
	@ResponseBody
	public ResponseVO typeupdata(@RequestParam("id") String id) {
		ResponseVO responseVO = new ResponseVO();
		responseVO.setStatus(200);
		RuleEnum ruleEnum = this.ruleEnumService.get(id);
		responseVO.setData(ruleEnum);
		return responseVO;
	}

	@RequestMapping("getType")
	@ResponseBody
	public String getType(RuleEnum ruleEnum) throws Exception {
		List<SelBean> list1 = new ArrayList<SelBean>();
		List<RuleEnum> list2 = new ArrayList<RuleEnum>();
		ruleEnum.setSearchEnumType(true);	
		ruleEnum.setProjectCode(this.getCurrProjectCode());
		list2 = ruleEnumDao.findList(ruleEnum);
		for (RuleEnum re : list2){
			list1.add(new SelBean(re.getEnumName(),re.getEnumCode())); //获取枚举类型管理页面类型名称	类型编码的集合
		}
		return JSONArray.toJSONString(list1);
	}
	
	//为了在新建变量选择变量类型为枚举时，弹出枚举项目选择框中使用checkbox出现的下拉框中可调用已定义的枚举变量类型(无用，与数据源相关)
    @RequestMapping("getParameter")
    public @ResponseBody
    JsonMessage getParameter(HttpServletRequest request) throws Exception {
        JsonMessage ret = new JsonMessage();
        try {
            String projectCode = this.getCurrProjectCode();
            List<DataSetTreeVo> resultList = ruleEnumService.findTypeListByProjCode(projectCode);
            ret.setData((Serializable) resultList);
        } catch (Exception e) {
            LoggerManager.error("", e, this.getClass());
            ret.setResult(false);
            ret.setMessage("获取数据模型失败");
        }
        return ret;
    }
    
    /**
	 * 获取数据库表的列对应的表内容信息
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "getTableData") 
	@ResponseBody
	public JsonMessage getTableData(String datasourceId,String tableName,int pageNo,int pageSize) {
		JsonMessage result = new JsonMessage();
		try {
			List<LinkedHashMap<String,Object>> resultEntity = dbtoDataModelService.getTableDataPage(datasourceId,tableName,pageNo,pageSize);
			result.setData((Serializable) resultEntity);
		} catch (Exception e) {
			LoggerManager.error("", e, this.getClass());
			result.setResult(false);
		}
		return result;
	} 
    
    /**
	 * 批量保存枚举项
	 * @param ruleEnumString
	 * @return
	 */
	@RequestMapping(value = "saveList")  
	@ResponseBody
	public String saveList(String ruleEnumString) {
		 ResMessage msg = null;
		try {
			String EnumString = StringEscapeUtils.unescapeHtml4(ruleEnumString);
			List<RuleEnum> ruleEnumList = JSON.parseArray(EnumString, RuleEnum.class);
			ruleEnumService.insertList(ruleEnumList);
			msg = new ResMessage("success", "保存成功");
		} catch (Exception e) {
			LoggerManager.error("", e, this.getClass());
			 msg = new ResMessage("failure", e.getMessage());
	          
		}
		return JSONArray.toJSONString(msg);
	} 
   
}